<template>
  <view class="favorites-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @tap="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="navbar-content">
        <text class="navbar-title">我的收藏</text>
      </view>
      <view class="navbar-action" @tap="toggleEditMode">
        <text class="action-text">{{ editMode ? '完成' : '编辑' }}</text>
      </view>
    </view>

    <!-- 分类标签 -->
    <view class="category-tabs">
      <view 
        class="category-tab" 
        :class="{ active: activeCategory === category.key }"
        v-for="category in categories" 
        :key="category.key"
        @tap="changeCategory(category.key)"
      >
        <text class="category-text">{{ category.label }}</text>
        <text class="category-count">({{ getCategoryCount(category.key) }})</text>
      </view>
    </view>

    <!-- 收藏列表 -->
    <view class="favorites-content">
      <view v-if="filteredFavorites.length === 0" class="empty-state">
        <text class="empty-icon">⭐</text>
        <text class="empty-title">暂无收藏</text>
        <text class="empty-desc">收藏你喜欢的课程和内容</text>
        <view class="empty-action" @tap="goToCourses">
          <text class="action-btn-text">去发现</text>
        </view>
      </view>

      <view v-else class="favorites-list">
        <!-- 课程收藏 -->
        <view v-if="activeCategory === 'all' || activeCategory === 'courses'" class="section">
          <view class="section-header" v-if="activeCategory === 'all' && courseFavorites.length > 0">
            <text class="section-title">课程收藏</text>
            <text class="section-count">{{ courseFavorites.length }}个</text>
          </view>
          
          <view class="course-grid">
            <view 
              class="course-item" 
              :class="{ 'edit-mode': editMode }"
              v-for="course in courseFavorites" 
              :key="course.id"
              @tap="handleCourseClick(course)"
            >
              <view class="course-cover">
                <image class="cover-image" :src="course.cover" mode="aspectFill"></image>
                <view class="course-type">
                  <text class="type-text">{{ getTypeLabel(course.type) }}</text>
                </view>
                <view class="select-overlay" v-if="editMode">
                  <view class="select-checkbox" :class="{ checked: selectedItems.includes(course.id) }">
                    <text class="checkbox-icon" v-if="selectedItems.includes(course.id)">✓</text>
                  </view>
                </view>
              </view>
              
              <view class="course-info">
                <text class="course-title">{{ course.title }}</text>
                <text class="course-duration">{{ course.duration }}</text>
                <text class="favorite-date">{{ formatDate(course.favoriteTime) }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 文章收藏 -->
        <view v-if="activeCategory === 'all' || activeCategory === 'articles'" class="section">
          <view class="section-header" v-if="activeCategory === 'all' && articleFavorites.length > 0">
            <text class="section-title">文章收藏</text>
            <text class="section-count">{{ articleFavorites.length }}个</text>
          </view>
          
          <view class="article-list">
            <view 
              class="article-item" 
              :class="{ 'edit-mode': editMode }"
              v-for="article in articleFavorites" 
              :key="article.id"
              @tap="handleArticleClick(article)"
            >
              <view class="article-cover">
                <image class="cover-image" :src="article.cover" mode="aspectFill"></image>
                <view class="select-overlay" v-if="editMode">
                  <view class="select-checkbox" :class="{ checked: selectedItems.includes(article.id) }">
                    <text class="checkbox-icon" v-if="selectedItems.includes(article.id)">✓</text>
                  </view>
                </view>
              </view>
              
              <view class="article-info">
                <text class="article-title">{{ article.title }}</text>
                <text class="article-desc">{{ article.description }}</text>
                <view class="article-meta">
                  <text class="meta-item">{{ article.category }}</text>
                  <text class="meta-item">{{ formatDate(article.favoriteTime) }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 测评收藏 -->
        <view v-if="activeCategory === 'all' || activeCategory === 'tests'" class="section">
          <view class="section-header" v-if="activeCategory === 'all' && testFavorites.length > 0">
            <text class="section-title">测评收藏</text>
            <text class="section-count">{{ testFavorites.length }}个</text>
          </view>
          
          <view class="test-list">
            <view 
              class="test-item" 
              :class="{ 'edit-mode': editMode }"
              v-for="test in testFavorites" 
              :key="test.id"
              @tap="handleTestClick(test)"
            >
              <view class="test-icon">
                <text class="icon-text">{{ getTestIcon(test.type) }}</text>
                <view class="select-overlay" v-if="editMode">
                  <view class="select-checkbox" :class="{ checked: selectedItems.includes(test.id) }">
                    <text class="checkbox-icon" v-if="selectedItems.includes(test.id)">✓</text>
                  </view>
                </view>
              </view>
              
              <view class="test-info">
                <text class="test-title">{{ test.title }}</text>
                <text class="test-desc">{{ test.description }}</text>
                <view class="test-meta">
                  <text class="meta-item">{{ test.questions }}题</text>
                  <text class="meta-item">{{ formatDate(test.favoriteTime) }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 编辑模式底部操作栏 -->
    <view class="edit-toolbar" v-if="editMode">
      <view class="toolbar-left">
        <view class="select-all" @tap="toggleSelectAll">
          <view class="select-checkbox" :class="{ checked: isAllSelected }">
            <text class="checkbox-icon" v-if="isAllSelected">✓</text>
          </view>
          <text class="select-text">全选</text>
        </view>
        <text class="selected-count">已选择 {{ selectedItems.length }} 项</text>
      </view>
      
      <view class="toolbar-actions">
        <view class="action-btn delete" @tap="deleteSelected" :class="{ disabled: selectedItems.length === 0 }">
          <text class="btn-text">删除</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeCategory: 'all',
      editMode: false,
      selectedItems: [],
      favorites: [],
      categories: [
        { key: 'all', label: '全部' },
        { key: 'courses', label: '课程' },
        { key: 'articles', label: '文章' },
        { key: 'tests', label: '测评' }
      ]
    }
  },
  
  computed: {
    courseFavorites() {
      return this.favorites.filter(item => item.type === 'course')
    },
    
    articleFavorites() {
      return this.favorites.filter(item => item.type === 'article')
    },
    
    testFavorites() {
      return this.favorites.filter(item => item.type === 'test')
    },
    
    filteredFavorites() {
      if (this.activeCategory === 'all') {
        return this.favorites
      }
      
      const typeMap = {
        courses: 'course',
        articles: 'article',
        tests: 'test'
      }
      
      return this.favorites.filter(item => item.type === typeMap[this.activeCategory])
    },
    
    isAllSelected() {
      return this.filteredFavorites.length > 0 && 
             this.selectedItems.length === this.filteredFavorites.length
    }
  },
  
  onLoad() {
    this.loadFavorites()
  },
  
  onShow() {
    this.loadFavorites()
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    loadFavorites() {
      try {
        // 加载课程收藏
        const courseFavorites = uni.getStorageSync('course_favorites') || []
        
        // 模拟文章和测评收藏数据
        const mockArticles = [
          {
            id: 'article_1',
            type: 'article',
            title: '如何管理焦虑情绪',
            description: '学会识别和应对日常生活中的焦虑情绪，建立健康的心理状态',
            cover: '/static/images/article1.jpg',
            category: '情绪管理',
            favoriteTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            id: 'article_2',
            type: 'article',
            title: '正念冥想的科学原理',
            description: '深入了解正念冥想对大脑和身心健康的积极影响',
            cover: '/static/images/article2.jpg',
            category: '冥想指导',
            favoriteTime: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString()
          }
        ]
        
        const mockTests = [
          {
            id: 'test_1',
            type: 'test',
            title: 'GAD-7 焦虑量表',
            description: '评估广泛性焦虑障碍的标准化量表',
            testType: 'anxiety',
            questions: 7,
            favoriteTime: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            id: 'test_2',
            type: 'test',
            title: 'PSS-10 压力感知量表',
            description: '测量个体对生活压力的主观感受程度',
            testType: 'stress',
            questions: 10,
            favoriteTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
          }
        ]
        
        // 转换课程收藏格式
        const formattedCourses = courseFavorites.map(course => ({
          ...course,
          type: 'course'
        }))
        
        this.favorites = [
          ...formattedCourses,
          ...mockArticles,
          ...mockTests
        ].sort((a, b) => new Date(b.favoriteTime) - new Date(a.favoriteTime))
        
      } catch (e) {
        console.error('加载收藏数据失败:', e)
        this.favorites = []
      }
    },
    
    changeCategory(category) {
      this.activeCategory = category
      this.exitEditMode()
    },
    
    getCategoryCount(category) {
      if (category === 'all') {
        return this.favorites.length
      }
      
      const typeMap = {
        courses: 'course',
        articles: 'article',
        tests: 'test'
      }
      
      return this.favorites.filter(item => item.type === typeMap[category]).length
    },
    
    toggleEditMode() {
      this.editMode = !this.editMode
      if (!this.editMode) {
        this.selectedItems = []
      }
    },
    
    exitEditMode() {
      this.editMode = false
      this.selectedItems = []
    },
    
    handleCourseClick(course) {
      if (this.editMode) {
        this.toggleSelection(course.id)
      } else {
        // 跳转到课程详情或播放页面
        uni.navigateTo({
          url: `/pages/course/meditation?id=${course.id}`
        })
      }
    },
    
    handleArticleClick(article) {
      if (this.editMode) {
        this.toggleSelection(article.id)
      } else {
        // 跳转到课程中心查看相关内容
        uni.navigateTo({
          url: '/pages/course/course'
        })
      }
    },
    
    handleTestClick(test) {
      if (this.editMode) {
        this.toggleSelection(test.id)
      } else {
        // 跳转到测评页面
        const testPages = {
          anxiety: '/pages/test/anxiety',
          stress: '/pages/test/stress',
          sleep: '/pages/test/sleep',
          'emotional-sensitivity': '/pages/test/emotional-sensitivity',
          'stress-tolerance': '/pages/test/stress-tolerance',
          'intrinsic-motivation': '/pages/test/intrinsic-motivation',
          'mindfulness-attention': '/pages/test/mindfulness-attention',
          'self-esteem': '/pages/test/self-esteem',
          'social-anxiety': '/pages/test/social-anxiety',
          'emotion-regulation': '/pages/test/emotion-regulation',
          'resilience': '/pages/test/resilience',
          'perfectionism': '/pages/test/perfectionism'
        }
        
        const page = testPages[test.testType]
        if (page) {
          uni.navigateTo({ url: page })
        } else {
          // 如果没有找到对应页面，跳转到自测中心
          uni.navigateTo({
            url: '/pages/test/test'
          })
        }
      }
    },
    
    toggleSelection(itemId) {
      const index = this.selectedItems.indexOf(itemId)
      if (index > -1) {
        this.selectedItems.splice(index, 1)
      } else {
        this.selectedItems.push(itemId)
      }
    },
    
    toggleSelectAll() {
      if (this.isAllSelected) {
        this.selectedItems = []
      } else {
        this.selectedItems = this.filteredFavorites.map(item => item.id)
      }
    },
    
    deleteSelected() {
      if (this.selectedItems.length === 0) return
      
      uni.showModal({
        title: '确认删除',
        content: `确定要删除选中的 ${this.selectedItems.length} 项收藏吗？`,
        success: (res) => {
          if (res.confirm) {
            this.confirmDelete()
          }
        }
      })
    },
    
    confirmDelete() {
      try {
        // 分类删除不同类型的收藏
        const courseIds = []
        const articleIds = []
        const testIds = []
        
        this.selectedItems.forEach(id => {
          const item = this.favorites.find(f => f.id === id)
          if (item) {
            switch (item.type) {
              case 'course':
                courseIds.push(id)
                break
              case 'article':
                articleIds.push(id)
                break
              case 'test':
                testIds.push(id)
                break
            }
          }
        })
        
        // 删除课程收藏
        if (courseIds.length > 0) {
          let courseFavorites = uni.getStorageSync('course_favorites') || []
          courseFavorites = courseFavorites.filter(course => !courseIds.includes(course.id))
          uni.setStorageSync('course_favorites', courseFavorites)
        }
        
        // 删除文章收藏（实际应用中需要实现）
        // 删除测评收藏（实际应用中需要实现）
        
        // 重新加载数据
        this.loadFavorites()
        this.exitEditMode()
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
      } catch (e) {
        console.error('删除收藏失败:', e)
        uni.showToast({
          title: '删除失败',
          icon: 'error'
        })
      }
    },
    
    goToCourses() {
      uni.switchTab({
        url: '/pages/course/course'
      })
    },
    
    getTypeLabel(type) {
      const labels = {
        meditation: '冥想',
        guidance: '疏导',
        breathing: '呼吸',
        sleep: '助眠'
      }
      return labels[type] || '课程'
    },
    
    getTestIcon(testType) {
      const icons = {
        anxiety: '😰',
        stress: '😤',
        sleep: '😴',
        depression: '😔'
      }
      return icons[testType] || '📋'
    },
    
    formatDate(dateString) {
      const date = new Date(dateString)
      const now = new Date()
      const diffTime = now - date
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays === 1) {
        return '昨天'
      } else if (diffDays < 7) {
        return `${diffDays}天前`
      } else if (diffDays < 30) {
        const weeks = Math.floor(diffDays / 7)
        return `${weeks}周前`
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`
      }
    }
  }
}
</script>

<style scoped>
.favorites-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding-bottom: 120rpx;
}

/* 导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 88rpx 40rpx 40rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-back .iconfont {
  font-size: 36rpx;
}

.navbar-content {
  flex: 1;
  text-align: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 600;
}

.navbar-action {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-text {
  font-size: 28rpx;
}

/* 分类标签 */
.category-tabs {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
}

.category-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  background: white;
  border-radius: 25rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.category-tab.active {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
}

.category-text {
  font-size: 28rpx;
  color: var(--text-secondary);
}

.category-count {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.category-tab.active .category-text,
.category-tab.active .category-count {
  color: white;
  font-weight: 600;
}

/* 收藏内容 */
.favorites-content {
  padding: 0 30rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;
  background: white;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 30rpx;
}

.empty-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 15rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: var(--text-secondary);
  display: block;
  margin-bottom: 40rpx;
}

.empty-action {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  padding: 24rpx 48rpx;
  border-radius: 25rpx;
  display: inline-block;
}

.action-btn-text {
  color: white;
  font-size: 28rpx;
  font-weight: 600;
}

/* 分组样式 */
.section {
  margin-bottom: 40rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
}

.section-count {
  font-size: 26rpx;
  color: var(--text-tertiary);
}

/* 课程网格 */
.course-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.course-item {
  width: calc(50% - 10rpx);
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.course-item.edit-mode {
  transform: scale(0.95);
  transition: transform 0.2s ease;
}

.course-cover {
  position: relative;
  height: 200rpx;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.course-type {
  position: absolute;
  top: 15rpx;
  right: 15rpx;
  background: rgba(0, 0, 0, 0.6);
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
}

.type-text {
  font-size: 22rpx;
  color: white;
}

.course-info {
  padding: 20rpx;
}

.course-title {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-duration {
  font-size: 24rpx;
  color: var(--text-secondary);
  display: block;
  margin-bottom: 8rpx;
}

.favorite-date {
  font-size: 22rpx;
  color: var(--text-tertiary);
}

/* 文章列表 */
.article-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.article-item {
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  display: flex;
  position: relative;
}

.article-item.edit-mode {
  transform: scale(0.98);
  transition: transform 0.2s ease;
}

.article-cover {
  position: relative;
  width: 200rpx;
  height: 150rpx;
  flex-shrink: 0;
}

.article-info {
  flex: 1;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.article-title {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.article-desc {
  font-size: 24rpx;
  color: var(--text-secondary);
  line-height: 1.5;
  display: block;
  margin-bottom: 15rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.article-meta {
  display: flex;
  gap: 20rpx;
}

.meta-item {
  font-size: 22rpx;
  color: var(--text-tertiary);
}

/* 测评列表 */
.test-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.test-item {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 20rpx;
  position: relative;
}

.test-item.edit-mode {
  transform: scale(0.98);
  transition: transform 0.2s ease;
}

.test-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: var(--accent-color);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.icon-text {
  font-size: 36rpx;
}

.test-info {
  flex: 1;
}

.test-title {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 10rpx;
}

.test-desc {
  font-size: 24rpx;
  color: var(--text-secondary);
  line-height: 1.5;
  display: block;
  margin-bottom: 15rpx;
}

.test-meta {
  display: flex;
  gap: 20rpx;
}

/* 选择覆盖层 */
.select-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.select-checkbox {
  width: 48rpx;
  height: 48rpx;
  border: 3rpx solid white;
  border-radius: 50%;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

.select-checkbox.checked {
  background: var(--primary-color);
  border-color: var(--primary-color);
}

.checkbox-icon {
  font-size: 24rpx;
  color: white;
  font-weight: bold;
}

/* 编辑工具栏 */
.edit-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 30rpx;
  border-top: 2rpx solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.select-all .select-checkbox {
  width: 36rpx;
  height: 36rpx;
  border: 2rpx solid var(--border-color);
  border-radius: 6rpx;
  background: white;
}

.select-all .select-checkbox.checked {
  background: var(--primary-color);
  border-color: var(--primary-color);
}

.select-all .checkbox-icon {
  font-size: 20rpx;
}

.select-text {
  font-size: 28rpx;
  color: var(--text-primary);
}

.selected-count {
  font-size: 26rpx;
  color: var(--text-secondary);
}

.toolbar-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  padding: 20rpx 40rpx;
  border-radius: 12rpx;
  min-width: 120rpx;
  text-align: center;
}

.action-btn.delete {
  background: #ffebee;
}

.action-btn.delete.disabled {
  background: var(--border-color);
}

.action-btn.delete .btn-text {
  color: #f44336;
  font-size: 28rpx;
  font-weight: 600;
}

.action-btn.delete.disabled .btn-text {
  color: var(--text-tertiary);
}
</style>